/*
 * Created on 23.01.2004
 * Local Projects Database
 * Mihai Postelnicu (mihai@ro-gateway.org)
 * (c) 2003 by eRomania Gateway
 */
package ro.gateway.aida.usr.messaging;

import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import ro.gateway.aida.db.DBPersistenceManager;
import ro.gateway.aida.db.DBWrapper;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.AIDALocation;
import ro.gateway.aida.obj.AIDAObjSector;
import ro.gateway.aida.obj.Activity;
import ro.gateway.aida.obj.GenericActivityProperty;
import ro.gateway.aida.obj.OrganizationInv;
import ro.gateway.aida.obj.OrganizationRole;
import ro.gateway.aida.obj.PersonInv;
import ro.gateway.aida.obj.db.ActivityDB;
import ro.gateway.aida.usr.Arbiter;



/**
 * @author Mihai Postelnicu<p>
 *
 *  e-mail (mihai@ro-gateway.org)<br>
 * (c) 2003 by eRomania Gateway<p>
 */
public class AlertDispacher extends DBPersistenceManager
{
      protected List alerters;
      protected List prjfilters;
      protected Activity a;
      protected DBWrapper db;
      protected AlertDB adb;
      protected Arbiter ar;
      protected ActivityDB actdb;

      public AlertDispacher( PersistenceToken token, Activity a )
      {
            super( token );
            //grab alerters and filters
            db = DBWrapper.getManager( token );
            adb = AlertDB.getManager( token );
            ar = Arbiter.getManager( token );
            actdb = ActivityDB.getManager( token );
            this.a = a;
      }

      protected void prepareDispatcher() throws Exception
      {
            alerters = ( List ) db.get( new Alerter( -1, -1 ) );
            prjfilters = ( List ) db.get( new ProjectFilter( -1, -1 ) );
      }

      protected void incAlerter( long id, boolean matched )
      {
            Iterator ia = alerters.iterator();
            while ( ia.hasNext() )
            {
                  Alerter al = ( Alerter ) ia.next();
                  if ( al.getId() == id )
                        al.incTotal();
                  if ( matched )
                        al.incMathed();
            }
      }

      protected void countMatched() throws Exception
      {
            Iterator ip = prjfilters.iterator();
            while ( ip.hasNext() )
            {
                  ProjectFilter pf = ( ProjectFilter ) ip.next();
                  incAlerter( pf.getAlerterId(), verifyFilter( pf ) );
            }
      }

      protected void sendAlert( Event e, Alerter al ) throws Exception
      {
            Alert alt = new Alert( e );
            alt.setAlertType( Alert.FILTER_ALERT );
            alt.setPriority( al.getPriority() );
            alt.setTo( al.getUserId() );
            alt.setByEmail( al.isMailable() );
            adb.add( alt );
      }

      public void sendAlerts( Event e ) throws Exception
      {
            prepareDispatcher();
            countMatched();
            Iterator ia = alerters.iterator();
            while ( ia.hasNext() )
            {
                  Alerter al = ( Alerter ) ia.next();
                  if ( al.isIntersection() )
                  {
                        if ( al.getMatchedCount() == al.getTotalCount() )
                              sendAlert( e, al );
                  }
                  else if ( al.getMatchedCount() > 0 )
                        sendAlert( e, al );
            }
      }

      protected boolean verifyFilter( ProjectFilter f ) throws Exception
      {
            boolean t = false;
            boolean one = false;
            int i;
            String[] l;

            //donor org
            OrganizationInv[] donor_orgs =
                  a.getOrgsByLRId( OrganizationRole.DONOR_ORG_ROLE );

            for ( i = 0, t = false;
                  ( donor_orgs != null ) && ( i < donor_orgs.length );
                  i++ )
                  if ( donor_orgs[ i ].getOrg().getId() == f.getDonorOrg() )
                  {
                        t = true;

                        break;
                  }

            if ( i != 0 && t == false )
                  return false;

            //beneficiary org
            OrganizationInv[] ben_orgs =
                  a.getOrgsByLRId( OrganizationRole.BENEFICIARS_ORG_ROLE );

            for ( i = 0, t = false; ( ben_orgs != null ) && ( i < ben_orgs.length ); i++ )
                  if ( ben_orgs[ i ].getOrg().getId() == f.getBeneficiaryOrg() )
                  {
                        t = true;

                        break;
                  }

            if ( i != 0 && t == false )
                  return false;

            //funding org
            OrganizationInv[] fun_orgs =
                  a.getOrgsByLRId( OrganizationRole.FINANCING_ORG_ROLE );

            for ( i = 0, t = false; ( fun_orgs != null ) && ( i < fun_orgs.length ); i++ )
                  if ( fun_orgs[ i ].getOrg().getId() == f.getFundingOrg() )
                  {
                        t = true;

                        break;
                  }

            if ( i != 0 && t == false )
                  return false;

            //contracting org
            OrganizationInv[] con_orgs =
                  a.getOrgsByLRId( OrganizationRole.CONTRACTING_ORG_ROLE );

            for ( i = 0, t = false; ( con_orgs != null ) && ( i < con_orgs.length ); i++ )
                  if ( con_orgs[ i ].getOrg().getId() == f.getContractingOrg() )
                  {
                        t = true;

                        break;
                  }

            if ( i != 0 && t == false )
                  return false;

            //sector
            AIDAObjSector[] ain_sectors = a.getSectors();

            for ( i = 0, t = false;
                  ( ain_sectors != null ) && ( i < ain_sectors.length );
                  i++ )
                  if ( ain_sectors[ i ].getSector().getRo_aida_code() == f.getSector() )
                  {
                        t = true;

                        break;
                  }

            if ( i != 0 && t == false )
                  return false;

            //location
            if ( f.getCountry_iso3() != null )
            {
                  AIDALocation[] ain_loc = a.getLocations();

                  for ( i = 0, t = false;
                        ( ain_loc != null ) && ( i < ain_loc.length );
                        i++ )
                        if ( ain_loc[ i ].getCountry()!=null && ain_loc[ i ].getCountry().getIso3()!=null &&
                        	ain_loc[i]
                              .getCountry()
                              .getIso3()
                              .equals( f.getCountry_iso3() ) )
                        {
                              t = true;

                              break;
                        }

                  if ( i != 0 && t == false )
                        return false;
            }

            //title
            if ( f.getTitle() != null && !f.getTitle().trim().equals( "" ) )
            {

                  GenericActivityProperty gen_titles = a.getGen_titles();
                  l = gen_titles.getAvailableLanguages();

                  for ( i = 0, t = false;
                        ( l != null ) && ( f.getTitle() != null ) && ( i < l.length );
                        i++ )
                  {
                        String title = gen_titles.getName( l[ i ] );

                        if ( title
                              .toLowerCase()
                              .matches( ".*" + f.getTitle().toLowerCase() + ".*" ) )
                        {
                              t = true;

                              break;
                        }
                  }

                  if ( i != 0 && t == false )
                        return false;
            }

            if ( f.getDescription() != null
                  && !f.getDescription().trim().equals( "" ) )
            {

                  //description
                  one = false;
                  t = false;

                  GenericActivityProperty gen_description = a.getGen_descriptions();
                  l = gen_description.getAvailableLanguages();

                  for ( i = 0;
                        ( l != null ) && ( f.getDescription() != null ) && ( i < l.length );
                        i++ )
                  {
                        one = true;
                        String name = gen_description.getName( l[ i ] );

                        if ( name
                              .toLowerCase()
                              .matches( ".*" + f.getDescription().toLowerCase() + ".*" ) )
                        {
                              t = true;

                              break;
                        }
                  }

                  //objectives
                  gen_description = a.getGen_objectives();
                  l = gen_description.getAvailableLanguages();

                  for ( i = 0;
                        ( l != null ) && ( f.getDescription() != null ) && ( i < l.length );
                        i++ )
                  {
                        one = true;
                        String name = gen_description.getName( l[ i ] );

                        if ( name
                              .toLowerCase()
                              .matches( "." + f.getDescription().toLowerCase() + "." ) )
                        {
                              t = true;

                              break;
                        }
                  }

                  //results
                  gen_description = a.getGen_results();
                  l = gen_description.getAvailableLanguages();

                  for ( i = 0;
                        ( l != null ) && ( f.getDescription() != null ) && ( i < l.length );
                        i++ )
                  {
                        one = true;
                        String name = gen_description.getName( l[ i ] );

                        if ( name
                              .toLowerCase()
                              .matches( "." + f.getDescription().toLowerCase() + "." ) )
                        {
                              t = true;

                              break;
                        }
                  }

                  if ( one && !t )
                        return false;
            }

            //keywords
            if ( f.getKeywords() != null )
            {
                  t = false;
                  one = false;

                  StringTokenizer st = new StringTokenizer( f.getKeywords(), "," );

                  while ( st.hasMoreTokens() )
                  {
                        one = true;
                        GenericActivityProperty gen_key = a.getGen_keywords();
                        l = gen_key.getAvailableLanguages();

                        for ( i = 0; ( l != null ) && ( i < l.length ); i++ )
                        {
                              String name = gen_key.getName( l[ i ] );

                              if ( name
                                    .toLowerCase()
                                    .matches( "." + st.nextToken().toLowerCase() + "." ) )
                              {
                                    t = true;

                                    break;
                              }
                        }
                  }

                  if ( one && !t )
                        return false;
            }

            //status
            if ( ( f.getStat() != -1 ) && a.getStatus()!=null && a.getStatus().getSt_code() != f.getStat() ) 
                  return false;

            //involved person
            PersonInv[] persons = a.getPersons();

            for ( i = 0, t = false; ( persons != null ) && ( i < persons.length ); i++ )
                  if ( persons[ i ].getPerson().getId() == f.getInvolvedPerson() )
                  {
                        t = true;

                        break;
                  }

            if ( i != 0 && !t )
                  return false;

            return true;
      }
}
